package cn.livingCloud.security;

import cn.livingCloud.context.SessionConstants;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义filter
 * 处理ajax 发送请求 session过期的情况
 * Created by 唐旭 on 2016/6/8.
 */
@Component
public class CustomUserFilter extends UserFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        boolean accessAllowed = super.isAccessAllowed(request, response, mappedValue);
        if (accessAllowed) {
            Subject subject = this.getSubject(request, response);
            Object attribute = subject.getSession().getAttribute(SessionConstants.USER_ACCOUNT_KEY);
            if (attribute != null) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = (HttpServletRequest) request;
            String header = req.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(header)) {
                outJsonData(response);
                return false;
            }
        }

        return super.onAccessDenied(request, response);
    }

    private void outJsonData(ServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append("<script>alert('登录过期!')</script>");
        } catch (IOException e) {
            throw new IOException(e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }
}
